package com.atguigu.common.utils;


import cn.hutool.core.text.CharSequenceUtil;
import io.jsonwebtoken.*;

import java.util.Date;

/**
 * 生成JSON Web令牌的工具类
 *
 * @author atguigu
 * @created 2022-10-26-0:52.
 */
public class JwtUtils {

    /**
     * token过期时间  365 天
     */
    private static final long TOKEN_EXPIRATION = 365 * 24 * 60 * 60 * 1000;
    /**
     * 加密秘钥
     */
    private static final String TOKEN_SIGN_KEY = "123456";

    /**
     * 根据用户id和用户名称生成token字符串
     *
     * @param userId
     * @param username
     * @return
     */
    public static String createToken(String userId, String username) {
        return Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 从token字符串获取userid
     *
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        try {
            if (CharSequenceUtil.isEmpty(token)) {
                return null;
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("userId");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从token字符串获取username
     */
    public static String getUsername(String token) {
        try {
            if (CharSequenceUtil.isEmpty(token)) {
                return "";
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String token = JwtUtils.createToken("1", "test");
        //log.info("token======>{}", token);

        String userId = JwtUtils.getUserId(token);
        //log.info("userId======>{}", userId);

        String username = JwtUtils.getUsername(token);
        //log.info("username======>{}", username);
    }
}
